package com.sgb.kjwl.view.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.MutableLiveData;
import androidx.viewpager.widget.ViewPager;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.android.material.tabs.TabLayout;
import com.im.immodel.IMUtils;
import com.sgb.kjwl.view.widget.self.permission.UserPermissionUtils;
import com.swgk.core.event.MessageEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.businessmodule.view.ui.activity.BusinessSearchActivity;
import com.sgb.businessmodule.view.ui.fragment.HomeBusinessOpportunitiesFragment;
import com.sgb.goods.entity.GoodsItemEntity;
import com.sgb.goods.view.activity.inquiry.NewPurchasesActivity;
import com.sgb.jicai.view.activity.JiCaiSearchActivity;
import com.sgb.jicai.view.fragment.CentralizedMiningFragment5;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentHome3Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.swgk.core.view.entity.ChannelEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.home.CityEntity;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.event.CategoryEvent;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.MainEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.PreferredChoiceActivity;
import com.sgb.kjwl.view.ui.activity.ScanActivity;
import com.sgb.kjwl.view.ui.activity.enterprise.ServiceSearchActivity;
import com.sgb.kjwl.view.ui.activity.home.ChooseAreaActivity;
import com.sgb.kjwl.view.ui.activity.home.HomeCategoryActivity;
import com.sgb.kjwl.view.ui.activity.home.SearchActivity5;
import com.sgb.kjwl.view.ui.activity.home.SearchShopFirstActivity;
import com.sgb.kjwl.view.ui.activity.home.TransportSearchActivity;
import com.sgb.kjwl.view.ui.activity.home.ZuLinSearchActivity;
import com.sgb.kjwl.view.ui.activity.manage.JingYingSearchActivity;
import com.sgb.kjwl.view.ui.activity.packers.PackersSearchActivity;
import com.sgb.kjwl.view.ui.activity.pick.PickSearchActivity;
import com.sgb.kjwl.view.ui.activity.self.SelfQrCodeActivity;
import com.sgb.kjwl.view.ui.activity.self.SuggestionFeedbackActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.authentication.CertificationActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.GoodsPublishActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.sgb.kjwl.view.ui.adapter.home.HomeFragmentPagerAdapter;
import com.sgb.kjwl.view.ui.fragment.home.BigHomeFragment3;
import com.sgb.kjwl.view.ui.fragment.home.EnterpriseFragment;
import com.sgb.kjwl.view.ui.fragment.home.EnterpriseManageFragment;
import com.sgb.kjwl.view.ui.fragment.home.FreightTransportFragment4;
import com.sgb.kjwl.view.ui.fragment.home.LeaseFragment3;
import com.sgb.kjwl.view.ui.fragment.home.MaterialHomeFragment1;
import com.sgb.kjwl.view.ui.fragment.packers.PackersChangeFragment;
import com.sgb.kjwl.view.widget.AddPopWindow;
import com.sgb.kjwl.view.widget.TitlePopWindow;
import com.sgb.kjwl.view.widget.member.CompanyChoosePopWindow;
import com.sgb.kjwl.viewmodel.home.HomeFragModel3;
import com.sgb.member.ui.fragment.HomeMemberFragment;
import com.sgb.merchant.view.fragment.MerchantHomeFragment;
import com.sgb.trip.view.fragment.TripHomeFragment;
import com.swgk.core.FlowLogUtils;
import com.swgk.core.base.BaseFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MessageEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.SharedPreferenceUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import static com.swgk.core.event.EventConstant.EVENT_GET_COUNT;
import static com.swgk.core.event.EventConstant.EVENT_GET_COUNT_TWO;
import static com.swgk.core.util.ACAdminDialogUtils.MK_ADDCOMMODITY;
import static com.swgk.core.util.ACAdminDialogUtils.MK_OURINQUIRYPRICELIST;


/**
 * Description:
 * Author zhengkewen
 * Time
 */
public class HomeFragment3 extends AppLazyFragment {
    public static final int MATERIAL = 0;
    public static final int PICK = 1;
    public static final int MACHINE = 2;
    public static final int DEVICE = 3;
    public static final int PACKERS = 4;
    public static final int POWER = 5;
    public static final int SET_FRGMENT = 10071;
    public static final String KEY_TYPE = "type";
    private FragmentHome3Binding binding;
    private TitlePopWindow titlePopWindow;
    private MainActivity activity;
    private int select = 0;
    private HomeFragmentPagerAdapter baseFragmentPagerAdapter;
    private AddPopWindow addPopWindow;
    private List<ChannelEntity> channelEntityList;
    //private String mCheckname;
    //private String mFristCheckName = "";
    private int mCheckId;
    private int mFristCheckId;
    private float unSelectedSize; //默认标题字体大小
    private float selectedSize; //选中时标题栏目字体大小
    @Inject
    HomeFragModel3 viewModel;
    private List<BaseFragment> chooseFragments = new ArrayList<>();
    private TextView selectTextView;
    private int type = EVENT_GET_COUNT;
    FreightTransportFragment4 freightTransportFragment4;
    private String enterpriseAuth = "";
    String driverAuth = "";
    //private String tabSelectName = "";
    private int tabSelectId;
    private boolean isFirst;
    private FlowLogUtils flowLogUtils;
    private BigHomeFragment3 bigHomeFragment3;
    private RequestManager requestManager;
    public MutableLiveData<Boolean> mChangeAreaLiveData = new MutableLiveData<>();
    private PackersChangeFragment mPackersChangeFragment;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            activity = (MainActivity) context;
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home3, container, false);
        Bundle bundle = this.getArguments();//得到从Activity传来的数据
        if (bundle != null) {
            mCheckId = bundle.getInt("checkId", -1);
        }
        selectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics());
        unSelectedSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 17, getResources().getDisplayMetrics());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        requestManager = Glide.with(this);
        binding.cityView.setText(viewModel.getCurrentLocal());
        initEtSearchView();
        initListener();
        SharedPreferenceUtil.init(getActivity());
        addPopWindow = new AddPopWindow(getActivity());
        addPopWindow.setOnClickCallBack(new AddPopWindow.OnClickCallBack() {
            @Override
            public void scan() {
                checkPermission();
            }

            @Override
            public void addFriend() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    //MToast.showToast(getMainActivity(), "功能暂未实现");
//                    AddFriendsActivity.start(getActivity());
                    IMUtils.getInstance().startFriend();
                }
            }

            @Override
            public void groupChat() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    //MToast.showToast(getMainActivity(), "功能暂未实现");
//                    activity.getGroupChat();
                    IMUtils.getInstance().startGroupChat();
                }
            }

            @Override
            public void qrCode() {
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //   MToast.showToast(this, "您还没有登录，请先登录");
                    VerificationCodeLoginActivity.start(getActivity(), false);
                } else {
                    SelfQrCodeActivity.start(getActivity());
                }
            }

            @Override
            public void feedback() {
                SuggestionFeedbackActivity.start(getActivity());
            }

          /*  @Override
            public void message() {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    activity.jumpLogin();
                } else {
                    activity.showChatView();
                }
            }*/
        });
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                select = i;
                //是否显示底部layout
//                showButtomLayout(i);
                scrollToPositionWithOffset(i, false);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void useModeNumToService(int tabSelectId) {
        if (tabSelectId != 21) {
            if (flowLogUtils == null) {
                flowLogUtils = new FlowLogUtils();
            }
            flowLogUtils.useModeNumToService6(tabSelectId);
        }
    }


    @SuppressLint({"AutoDispose", "CheckResult"})
    @Override
    protected void onLazyLoad() {
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    viewModel.getChannelList();
                });
        viewModel.getLocalProvince();
        getLocation();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && tabSelectId == 6) {
            if (!LocationUtil.isLocServiceEnable(getContext())) {
                new RoundDialog.Builder(getActivity())
                        .title("系统定位服务已关闭")
                        .content("请打开定位服务，以便我们为您提供更近的货源")
                        .confirmCallback(v -> {
                            LocationUtil.openGPS(getContext());
                        })
                        .show();
            }
        }
    }

    @Override
    public void onVisible() {
        super.onVisible();
        //当选中会员时，对顶部布局样式初始化
        refreshMemberTopStatus();
    }

    public void getChannel(List<ChannelEntity> channelEntityListNew) {
        this.channelEntityList = channelEntityListNew;
        for (ChannelEntity list : channelEntityList) {
            if (list.getId() == 19) {
                channelEntityList.remove(list);
                break;
            }
        }
        initTatleTab();
        //初始化顶部Tab顺序列表
        initTitlePopWindow();
    }

    private void initTabToViewPage() {
        if (binding == null) return;
        binding.tablayout.clearOnTabSelectedListeners();
        binding.tablayout.removeAllTabs();
        setFragmentV(channelEntityList);
        baseFragmentPagerAdapter = new HomeFragmentPagerAdapter(getChildFragmentManager(), chooseFragments, channelEntityList);
        binding.viewpager.setAdapter(baseFragmentPagerAdapter);
        binding.viewpager.setVisibility(View.VISIBLE);
            binding.viewpager.setOffscreenPageLimit(channelEntityList.size());
            binding.tablayout.setupWithViewPager(binding.viewpager);
        setupTabView();
        initHomeTabListener();
        binding.viewpager.setCurrentItem(1);
        binding.viewpager.setCurrentItem(0); //直接设置选中0位置不起作用，固先设置先选中1再选中0
    }

    /**
     * 自定义tab样式
     */
    private void setupTabView() {
        tabSelectId = channelEntityList.get(0).getId();
        for (int i = 0; i < channelEntityList.size(); i++) {
            TabLayout.Tab tab = binding.tablayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
                tab.setTag(channelEntityList.get(i).getId());
            }
        }
    }

    private View getTabView(int position) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_home_tab_menu, null);
        ImageView iv = view.findViewById(R.id.iv_tabItem);
        getMenuDrawable(channelEntityList.get(position).getId(), iv);
        return view;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void getMenuDrawable(int id, ImageView iv) {
        if (iv == null) return;
        if (getMainActivity() == null) return;
        switch (id) {
            case 21:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_home_menu_iv));
                break;
            case 1:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_commodity_menu_iv));
                break;
            case 3:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_pick_menu_iv));
                break;
            case 4:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_lease_menu_iv));
                break;
            case 6:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_logistics_menu_iv));
                break;
            case 5:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_packers_menu_iv));
                break;
            case 22:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_com_service_iv));
                break;
            case 23:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_com_operating_menu_iv));
                break;
            case 28:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_business_menu_iv));
                break;
            case 24:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_member_menu_iv));
                break;
            case 27:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_merchants_menu_iv));
                break;
            case 2:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_bidding_menu_iv));
                break;
            case 31:
                iv.setImageDrawable(ContextCompat.getDrawable(getMainActivity(), R.drawable.it_trip_menu_iv));
                break;
        }
    }

    private void initHomeTabListener() {
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tabSelectId = (int) tab.getTag();
                //TODO 大首页永远不调用统计次数
                useModeNumToService(tabSelectId);
                //对第一个固定按钮的初始化
                initFirstTabView();
                //初始化切换TabLayout控件时，对顶部布局初始化
                initTitleTopView(tabSelectId, tab.getPosition());
                //当切换到某个功能模块需要发消息时，目前
                refreshMemberTopStatus();
                //todo 添加切换tab事件改变底部菜单
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().postSticky(MenuEvent.make(EventConstant.EVENT_CHANGE_TAB, tabSelectId));
                    }
                }, 300);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ImageView iv = tab.getCustomView().findViewById(R.id.iv_tabItem);
                iv.setSelected(false);
                iv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 界面控件点击事件初始化
     */
    private void initListener() {
        binding.cityView.setOnClickListener(this);
        binding.roleLayout.setOnClickListener(this);
        binding.editView.setOnClickListener(this);
        binding.addView.setOnClickListener(this);
        binding.searchView.setOnClickListener(this);
        binding.imgMore.setOnClickListener(this);
        binding.etSearch.setOnClickListener(this);
        binding.tvRz.setOnClickListener(this);
        binding.tvZc.setOnClickListener(this);
        binding.tvFb.setOnClickListener(this);
        binding.tvXj.setOnClickListener(this);
        binding.tvSj.setOnClickListener(this);
        binding.homeShare.setOnClickListener(this);
        binding.homeFirstLin.setOnClickListener(this);
        binding.zhaocaiSearch.setOnClickListener(this);
        binding.issue.setOnClickListener(this);
    }

    /**
     * 对第一个固定按钮的初始化
     */
    private void initFirstTabView() {
        if (tabSelectId == mFristCheckId) {
            binding.homeFirst.setSelected(true);
        } else {
            binding.homeFirst.setSelected(false);
        }
    }

    /**
     * 初始化切换TabLayout控件时，对顶部布局初始化
     */
    private void initTitleTopView(int tabSelectId, int tabPosition) {
        if (tabSelectId == 1) {
            binding.rlEtView.setVisibility(View.GONE);
            binding.searchView.setVisibility(View.VISIBLE);
            binding.imgMore.setVisibility(View.VISIBLE);
            binding.tvZc.setVisibility(View.GONE);
            binding.tvRz.setVisibility(View.GONE);
            binding.etSearch.setVisibility(View.INVISIBLE);
            binding.tvSj.setVisibility(View.GONE);
            binding.tvGz.setVisibility(View.GONE);
            binding.tvFb.setVisibility(View.VISIBLE);
            binding.tvXj.setVisibility(View.VISIBLE);
            binding.issue.setVisibility(View.GONE);
            binding.zhaocaiSearch.setVisibility(View.GONE);
        } else {
            binding.tvFb.setVisibility(View.GONE);
            binding.tvXj.setVisibility(View.GONE);
            binding.tvGz.setVisibility(View.GONE);
            binding.tvRz.setVisibility(View.GONE);
            binding.tvZc.setVisibility(View.GONE);
            binding.tvSj.setVisibility(View.GONE);
            binding.imgMore.setVisibility(View.GONE);
            binding.etSearch.setVisibility(View.INVISIBLE);
            binding.rlEtView.setVisibility(View.GONE);
            binding.issue.setVisibility(View.GONE);
            binding.zhaocaiSearch.setVisibility(View.GONE);
            if (tabSelectId == 21) {
                binding.rlEtView.setVisibility(View.VISIBLE);
                binding.searchView.setVisibility(View.GONE);
                binding.etSearch.setVisibility(View.GONE);
//                        binding.tvSj.setVisibility(View.VISIBLE);
//                        binding.tvGz.setVisibility(View.VISIBLE);
                // binding.tvRz.setVisibility(View.VISIBLE);
            } else if (tabSelectId == 4) {
                binding.searchView.setVisibility(View.VISIBLE);
            } else if (tabSelectId == 6) {
                binding.searchView.setVisibility(View.VISIBLE);
                binding.tvFb.setVisibility(View.GONE);
                binding.tvSj.setVisibility(View.GONE);
                binding.tvRz.setVisibility(View.VISIBLE);
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    binding.tvZc.setVisibility(View.VISIBLE);
                } else {
                    binding.tvZc.setVisibility(View.GONE);
                }

            } else if (tabSelectId == 5) {
                binding.searchView.setVisibility(View.VISIBLE);
            } else if (tabSelectId == 3) {
//                        binding.etSearch.setVisibility(View.VISIBLE);
//                        binding.etSearch.setHint("请输入商品或集采地或发起方");
                binding.etSearch.setVisibility(View.INVISIBLE);
                binding.searchView.setVisibility(View.VISIBLE);
            } else if (tabSelectId == 2) {
                binding.searchView.setVisibility(View.GONE);
                binding.issue.setVisibility(View.VISIBLE);
                binding.etSearch.setVisibility(View.GONE);
                binding.zhaocaiSearch.setVisibility(View.VISIBLE);
            } else if (channelEntityList.get(tabPosition).getId() == 22) {
                //企业服务
                binding.etSearch.setVisibility(View.VISIBLE);
                binding.etSearch.setHint("请输入关键字");
            } else if (tabSelectId == 24) {
                binding.searchView.setVisibility(View.GONE);
            } else if (tabSelectId == 28) {
                binding.searchView.setVisibility(View.VISIBLE);
            } else if (tabSelectId == 23) {
                binding.searchView.setVisibility(View.GONE);
                binding.etSearch.setVisibility(View.VISIBLE);
                binding.etSearch.setHint("请输入关键字");
            }
        }
    }

    /**
     * 初始化tabLayout控件自定义样式
     */
    private void initTitleView() {
        if (channelEntityList != null && channelEntityList.size() > 0) {
            if (tabSelectId == channelEntityList.get(0).getId()) {
                binding.homeFirst.setSelected(true);
            } else {
                binding.homeFirst.setSelected(false);
            }
           /* if (!TextUtils.isEmpty(mCheckname)) {
                mFristCheckName = mCheckname;
                getMenuDrawable(mCheckname, binding.homeFirst);
            } else {
                mFristCheckName = channelEntityList.get(0).getName();
                getMenuDrawable(channelEntityList.get(0).getName(), binding.homeFirst);
            }*/
            mFristCheckId = mCheckId;
            getMenuDrawable(mCheckId, binding.homeFirst);
        }

        if (tabSelectId == 6) {//物流
            if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                binding.tvZc.setVisibility(View.VISIBLE);
            } else {
                viewModel.getUserInfo();
                binding.tvZc.setVisibility(View.GONE);
            }
        }
        //对当将会员固定为第一个位置时，对顶部的初始化
        refreshMemberTopStatus();
    }

    /**
     * 初始化顶部Tab顺序列表
     */
    private void initTitlePopWindow() {
        titlePopWindow = new TitlePopWindow(getActivity(), channelEntityList);
        //titlePopWindow.setBgView(binding.grayLayout);
        titlePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!titlePopWindow.isShowing()) {
                    binding.ivEdit.setRotation(0);
                }
            }
        });
        titlePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                channelEntityList = (List<ChannelEntity>) key1;
                //存入本地
                Observable.timer(200, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> {
                            DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, channelEntityList);
                            initTatleTab();
                        });
            }
        });
    }

    private void initTatleTab() {
        mCheckId = channelEntityList.get(0).getId();
        mFristCheckId = channelEntityList.get(0).getId();
        initTitleView();
        getMenuDrawable(mCheckId, binding.homeFirst);
        binding.homeFirst.setSelected(true);
        chooseFragments.clear();
        initTabToViewPage();
    }

    private void setFragmentV(List<ChannelEntity> channelEntityList) {
        ArrayList<ChannelEntity> shareList = new ArrayList<>();
        shareList.addAll(channelEntityList);

        chooseFragments.clear();
        for (int i = 0; i < channelEntityList.size(); i++) {
            if (channelEntityList.get(i).getId() == 21) {
                //首页 21
                if (!TextUtils.isEmpty(channelEntityList.get(i).getName())) {
                    chooseFragments.add(bigHomeFragment3 = BigHomeFragment3.newInstance(channelEntityList.get(i).getName()));
                }
            } else if (channelEntityList.get(i).getId() == 1) {
                //商品 1
                chooseFragments.add(MaterialHomeFragment1.newInstance(channelEntityList.get(i).getName()));
            } else if (channelEntityList.get(i).getId() == 2) {
                //招采 2
                chooseFragments.add(MainRecruitmentFragment.newInstance(channelEntityList.get(i).getName()));
            } else if (channelEntityList.get(i).getId() == 4) {
                //租赁 4
                chooseFragments.add(LeaseFragment3.newInstance(channelEntityList.get(i).getName()));
            } else if (channelEntityList.get(i).getId() == 22) {
                //服务 7
                chooseFragments.add(EnterpriseFragment.newInstance());
            } else if (channelEntityList.get(i).getId() == 5) {
                mPackersChangeFragment = PackersChangeFragment.newInstance();
                //工队 5
                chooseFragments.add(mPackersChangeFragment);
            } else if (channelEntityList.get(i).getId() == 6) {
                //物流 6
                if (!TextUtils.isEmpty(channelEntityList.get(i).getName())) {
                    chooseFragments.add(freightTransportFragment4 = FreightTransportFragment4.newInstance(channelEntityList.get(i).getName()));
                }
            } else if (channelEntityList.get(i).getId() == 3) {
                //集采 3
                chooseFragments.add(CentralizedMiningFragment5.newInstance());
            } else if (channelEntityList.get(i).getId() == 23) {
                //企业经营
                chooseFragments.add(EnterpriseManageFragment.newInstance());
            } else if (channelEntityList.get(i).getId() == 24) {
                //会员经营
                chooseFragments.add(HomeMemberFragment.newInstance());
            } else if (channelEntityList.get(i).getId() == 27) {
                //招商引资
                chooseFragments.add(MerchantHomeFragment.newInstance());
            } else if (channelEntityList.get(i).getId() == 28) {
                //商机服务
                chooseFragments.add(HomeBusinessOpportunitiesFragment.newInstance());
            } else if (channelEntityList.get(i).getId() == 31) {
                //食住行
                chooseFragments.add(TripHomeFragment.newInstance());
            }
        }
    }

    /**
     * 初始化 首页搜索功能
     */
    private void initEtSearchView() {
        binding.etSearchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etSearchView.setText("");
            }
        });
        binding.etSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    binding.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        binding.etSearchView.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    SearchActivity5.start(getActivity(), binding.etSearchView.getText().toString());
                    KeyboardUtils.hideSoftInput(binding.etSearchView);
                }
                return false;
            }
        });
    }

    /**
     * 当选中会员时，对顶部布局样式初始化
     */
    private void refreshMemberTopStatus() {
        binding.cityView.setVisibility(View.VISIBLE);
        binding.roleLayout.setVisibility(View.GONE);
        if (binding.tablayout.getTabCount() > 0) {
            int tabPosition = binding.tablayout.getSelectedTabPosition();
            TabLayout.Tab tab = binding.tablayout.getTabAt(tabPosition);
            if (tab != null) {
                // 会员新添加顶部角色切换按钮
                if ("会员经营".equals(Objects.requireNonNull(tab.getText()).toString())) {
                    // 1、未登录状态显示定位城市定位按钮, 登录状态显示用户中心头像，不可点击
                    String saveStringData = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "");
                    if (!"".equals(saveStringData)) {
                        // 登录【认证个人/认证企业】
                        if (mCompanyData == null || mCompanyData.size() == 0) {
                            mCompanyData = new ArrayList<>();
                            mOriCompanyNo = "-1";
                            viewModel.getCompanyList();
                        } else {
                            showCompanyList(mCompanyData);
                        }
                    } else {
                        mOriCompanyNo = "-1";
                        int selectedTabPosition = binding.tablayout.getSelectedTabPosition();
                        BaseFragment baseFragment = chooseFragments.get(selectedTabPosition);
                        if (baseFragment != null && baseFragment instanceof HomeMemberFragment) {
                            ((HomeMemberFragment) baseFragment).onVisible();
                        }
                    }
                }
            }
        }
    }

    private void showTitlePop() {
        if (titlePopWindow != null) {
            titlePopWindow.showPopwindow0(binding.lineView);
            titlePopWindow.backgroundAlpha(0.5f);
            titlePopWindow.setInitialization();
            binding.ivEdit.setRotation(180);
        }
    }

    public void showAreaName(String cityName) {
        if (!cityName.contains("省")) {
            if (cityName.contains("内蒙古") || cityName.contains("黑龙江")) {
                cityName = cityName.substring(0, 3);
            } else {
                cityName = cityName.substring(0, 2);
            }
        } else {
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        binding.cityView.setText(cityName);
        refershCheardFragment();
        int selectTab = binding.tablayout.getSelectedTabPosition();
        String tabTitle = binding.tablayout.getTabAt(selectTab).getText().toString();
        if (!tabTitle.equals(mFristCheckId)) {
            if (chooseFragments.get(selectTab) instanceof MainRecruitmentFragment) {
                ((MainRecruitmentFragment) chooseFragments.get(selectTab)).showAreaName();
            }
        }
    }

    private void refershCheardFragment() {
        //切换城市后刷新首页数据
        if (tabSelectId == 21) {
            if (bigHomeFragment3 != null) {
                bigHomeFragment3.refreshHomeData();
            }
        }
        mChangeAreaLiveData.postValue(true);

    }

    public void goLogin(Context context) {
        //传false根据菜单权限来判断
        int type = ACAdminDialogUtils.isPermissionForAsk(MK_OURINQUIRYPRICELIST, false);
        if (type == ACAdminDialogUtils.TYPE_NORMAL) {
            viewModel.getUserInfoCheck();
        } else {
            ACAdminDialogUtils.showACDialogForGoods(type, context);
        }
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onMultiClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.home_share:
                SharePermissionUtils.getPermission(getActivity());
                //  HomeShare2Activity.start(getContext());
                break;
            case R.id.home_first_lin:
                binding.viewpager.setCurrentItem(0);
                break;
            case R.id.city_view:
                //todo 暂时注释城市切换，使用省份切换
                ChooseAreaActivity.start(getActivity(), select);
                //城市切换
//                ChoiceCityActivity.start(getActivity());
//                IntelligentAttentionActivity.start(getActivity());
//                MonitoringReportActivity.start(getActivity());
                break;
            case R.id.edit_view:
                showTitlePop();
                break;
            case R.id.tv_fb:
//                if (binding.tablayout.getSelectedTabPosition() != 6) {
                String RELEVANCE = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.RELEVANCE, "");
                boolean IS_GOODS_PUBLISH = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.CHILD_MENU, "").contains(MK_ADDCOMMODITY);
                if (tabSelectId != 6) {
                    if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        ACAdminDialogUtils.showACDialogForPublish(ACAdminDialogUtils.TYPE_NO_LOGIN, getActivity(), null);
                        return;
                    } else {
                        if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                            ACAdminDialogUtils.showACDialogForPublish(3, getContext(), new ACAdminDialogUtils.DialogClick() {
                                @Override
                                public void dialogClick1() {
                                    CertificationActivity.start(getContext());
                                }
                            });
                            break;
                        } else if (SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false)) {
                            if ("SUCCESS".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "")) || RELEVANCE.equals("1")) {
                                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "").equals("个人中心")) {
                                    ACAdminDialogUtils.showACDialogForPublish(1, getContext(), new ACAdminDialogUtils.DialogClick() {
                                        @Override
                                        public void dialogClick3() {
                                            activity.displayFrg(3);
                                        }
                                    });
                                    break;
                                } else {
                                    if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.IS_DATA, "").contains("3_shangpinfabu")) {
                                        GoodsPublishActivity.start(getActivity());
                                    } else {
                                        MToast.showToast(getContext(), "您没有权限，请联系管理员开通");
                                    }
                                }
                            } else {
                                ACAdminDialogUtils.showACDialogForPublish(4, getContext(), new ACAdminDialogUtils.DialogClick() {
                                    @Override
                                    public void dialogClick2() {
                                        activity.displayFrg(3);
                                    }
                                });
                                break;
                            }
//                            else if (!"SUCCESS".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "")) && IS_GOODS_PUBLISH) {
//                                GoodsPublishActivity.start(getActivity());
//                            } else if (!"SUCCESS".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "")) && !IS_GOODS_PUBLISH && !"1".equals(RELEVANCE)) {
//                                AuthActivity.start(getActivity());
//                            } else if (!"SUCCESS".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "")) && !IS_GOODS_PUBLISH && "1".equals(RELEVANCE)) {
//                                ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_NO_PERMISSION, getActivity());
//                            }
//                            }else {
//
//                            }
                        }


                    }
                } else {
                    if (freightTransportFragment4 != null) {
                        freightTransportFragment4.publicTransport();
                    }
                }
                break;
            case R.id.tv_xj:
                goLogin(getActivity());
                break;
            case R.id.add_view:
                addPopWindow.showPopwindow(binding.addView, true);
                break;
            case R.id.zhaocai_search:
                PickSearchActivity.start(getActivity());//需求预告1.2.0修改招标竞价搜索样式
                break;
            case R.id.issue:
                if (getActivity() instanceof MainActivity) {
                    MainActivity main = (MainActivity) getActivity();
                    main.showPopZhaoCai();
                }
                break;
            case R.id.et_search:
                if (tabSelectId == 3) {
                    JiCaiSearchActivity.start(getActivity());
                } else if (tabSelectId == 22) {
                    ServiceSearchActivity.start(getActivity());
                } else if (tabSelectId == 23) {
                    JingYingSearchActivity.start(getActivity());
                }
                break;
            case R.id.search_view:
                if (tabSelectId == 21) {
                    SearchActivity5.start(getActivity());
                    return;
                } else if (tabSelectId == 6) {
                    TransportSearchActivity.start(getActivity());
                } else if (tabSelectId == 2) {
                    PickSearchActivity.start(getActivity());
                } else if (tabSelectId == 5) { // 工队
                    PackersSearchActivity.start(getActivity());
                    return;
                } else if (tabSelectId == 3) {
                    JiCaiSearchActivity.start(getActivity());
                } else if (tabSelectId == 4) {
                    ZuLinSearchActivity.start(getActivity());
                } else if (tabSelectId == 28) {
                    if (isAuth()) {
                        BusinessSearchActivity.start(getActivity());
                    }
                } else {
                    SearchShopFirstActivity.start(getActivity(), false);
                }



                /*if (binding.tablayout.getSelectedTabPosition() == 0) {
                    SearchActivity4.start(getActivity(), true);
                    return;
                } else if (binding.tablayout.getSelectedTabPosition() == 6) {//物流
                    TransportSearchActivity.start(getActivity());
                } else if (binding.tablayout.getSelectedTabPosition() == 5) { // 工队
                    PackersSearchActivity.start(getActivity());
                    return;
                } else {                    SearchActivity4.start(getActivity(), false);
                }*/

                 /*   if (binding.tablayout.getSelectedTabPosition() == 6) {//物流
                    LogisticsSearchActivity3.start(getActivity(), 0);
                } else {
                    SearchActivity3.start(getActivity(), 0);
                }*/
                break;
            case R.id.img_more:
                //工程材料
                EventBus.getDefault().postSticky(CategoryEvent.make(EventConstant.EVENT_CATEGORY_CHOOSE, 0));
                HomeCategoryActivity.start(getActivity(), false);
                break;
            case R.id.tv_rz:
                //物流认证弹框
                // showDialog();
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getActivity());
                    return;
                }
                //更改调到认证中心
                AuthActivity3.start(getContext());
                break;
            case R.id.tv_zc:
                VerificationCodeLoginActivity.start(getActivity());
                break;
            case R.id.tv_sj:
                if (tabSelectId == 6) {
                    if (freightTransportFragment4 != null) {
                        freightTransportFragment4.business();
                    }
                }
                break;
            case R.id.role_layout:
                // 会员角色切换
                // 2、未登录状态跳转到登录界面, 登录状态显示用户中心头像，不可点击
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    VerificationCodeLoginActivity.start(getContext());
                } else {
                    // 登录【认证个人/认证企业】
                    if (mCompanyData == null || mCompanyData.size() == 0) {
                        viewModel.getCompanyList();
                        return;
                    }
                    showCompanyPopup();
                }
                break;
        }
    }

    // 获取用户企业
    private List<CompanyEntity> mCompanyData;
    private CompanyChoosePopWindow companyChangePop;
    private String mOriCompanyNo = "-1";

    public void showCompanyList(List<CompanyEntity> data) {
        mCompanyData = new ArrayList<>();
        mCompanyData.addAll(data);
        //判断是否存在（以前的公共接口，无公司也返回一个空公司，暂时用公司名判断是否存在）
        if (data.size() > 0 && !TextUtils.isEmpty(data.get(0).getCompName())) {
            //展示公司的弹窗
            binding.cityView.setVisibility(View.GONE);
            binding.roleLayout.setVisibility(View.VISIBLE);
            //循环取出list集合中的每一个CompanyEntity对象
            String no = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
            for (CompanyEntity company : data) {
                //找到主企业
                if (null != company && company.getCompNo().equals(no)) {
                    setCurrentCompany(company);
                    break;
                }
            }
            //如果只有一个公司时，将向上或向下的图标隐藏
            if (data.size() == 1) {
                binding.companyDown.setVisibility(View.GONE);
            }//如果不止一个公司时，将向上或向下的图标显示
            else {
                binding.companyDown.setVisibility(View.VISIBLE);
            }
        } else {
            //如果没有公司则隐藏公司列表
            binding.roleLayout.setVisibility(View.GONE);
        }
    }

    private void showCompanyPopup() {
        if (companyChangePop == null) {
            companyChangePop = new CompanyChoosePopWindow(getActivity());
            companyChangePop.setDialogClickCallBack(new CompanyChoosePopWindow.DialogClickCallBack() {
                @Override
                public void onItemClick(CompanyEntity provinceEntity, int position) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, provinceEntity.getType());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, provinceEntity.getCompNo());
                    viewModel.settingMainCompany(provinceEntity);
                    viewModel.getEssentialInformation(provinceEntity);
                    companyChangePop.setItem(position);
                    companyChangePop.dismiss();
                }
            });
        }
        //公司弹窗设置参数集合
        companyChangePop.setData(mCompanyData);
        //展示显示弹窗
        companyChangePop.showPopwindow0(binding.roleLayout);
    }

    // 设置主企业
    public void setCurrentCompany(CompanyEntity companyEntity) {
        int comType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        if (comType == 0) {
            String realName = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, "");
            binding.tvRoleName.setText(realName);
        } else {
            binding.tvRoleName.setText(companyEntity.getCompName());
        }
        setHeadImg(companyEntity.getCompLogo(), companyEntity.getType());
        mOriCompanyNo = companyEntity.getCompNo();
        EventBus.getDefault().postSticky(EventConstant.EVENT_REFRESH_MAIN);
        EventBus.getDefault().postSticky(MainEvent.make(EventConstant.EVENT_MAIN_ENTERPRISE_SWITCHING, 0));
        int selectedTabPosition = binding.tablayout.getSelectedTabPosition();
        BaseFragment baseFragment = chooseFragments.get(selectedTabPosition);
        if (baseFragment != null && baseFragment instanceof HomeMemberFragment) {
            ((HomeMemberFragment) baseFragment).onVisible();
        }
    }

    public void setHeadImg(String url, int type) {
        if (!TextUtils.isEmpty(url)) {
            if (type == 1) {
                //Glide展示图片
                Glide.with(this)
                        //加载设置宽高限制
                        .load(url + "?x-oss-process=image/resize,m_fixed,h_250")
                        //显示圆图
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(1)))
                        //设置为头像
                        .into(binding.ivRole);
            } else {
                //Glide展示图片
                Glide.with(this)
                        //加载设置宽高限制
                        .load(url + "?x-oss-process=image/resize,m_fixed,h_250")
                        //显示圆图
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        //设置为头像
                        .into(binding.ivRole);
            }

        } else {
            ////Glide展示图片，如果没有用户头像则显示默认头像
            if (type == 0) {
                binding.ivRole.setImageResource(R.mipmap.def_photo);
            } else if (type == 1) {
                binding.ivRole.setImageResource(R.mipmap.shop_img_new_2);
            } else {
                binding.ivRole.setImageResource(R.drawable.icon_team_default);
            }
        }
    }

    public void showRz() {
        enterpriseAuth = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "");
        driverAuth = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DRIVER_AUTH, "");
        if ("SUCCESS".equals(enterpriseAuth) || driverAuth.equals("SUCCESS")) {
            binding.tvRz.setVisibility(View.GONE);
        } else {
            binding.tvRz.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 新市级地区选择（等待时机启用）
     *
     * @param cityEntity
     */
    public void showChangeDialog(CityEntity cityEntity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = builder.setTitle("您当前位置在" + cityEntity.getCityName()).setMessage("是否确定切换到" + cityEntity.getCityName()).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ProvinceEntity provinceEntity = new ProvinceEntity();
                provinceEntity.setShortName(cityEntity.getCityName());
                provinceEntity.setId(cityEntity.getGrade());
                selectCity(provinceEntity);
            }
        }).setCancelable(true).create();
        alertDialog.show();
        Window dialogWindow = alertDialog.getWindow();
        WindowManager m = activity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        // 设置宽度
        p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
        p.gravity = Gravity.CENTER;//设置位置
        //p.alpha = 0.8f;//设置透明度
        dialogWindow.setAttributes(p);

    }

    /**
     * //todo 暂时注释城市切换，使用下面省份切换通知
     * 原省级地区选择（暂时保留使用）
     *
     * @param provinceEntity
     */
    public void showChangeDialog(ProvinceEntity provinceEntity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = builder.setTitle("您当前位置在" + provinceEntity.getAreaName()).setMessage("是否确定切换到" + provinceEntity.getAreaName()).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                selectCity(provinceEntity);
            }
        }).setCancelable(true).create();
        alertDialog.show();
        Window dialogWindow = alertDialog.getWindow();
        WindowManager m = activity.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        // 设置宽度
        p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
        p.gravity = Gravity.CENTER;//设置位置
        //p.alpha = 0.8f;//设置透明度
        dialogWindow.setAttributes(p);

    }

    private void checkPermission() {
        if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            activity.jumpLogin();
            return;
        }

        if (PermissionsUtil.hasPermission(getActivity(), Manifest.permission.CAMERA)) {
            ScanActivity.start(getActivity());
        } else {
            PermissionsUtil.requestPermission(getActivity(), new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    ScanActivity.start(getActivity());
                }

                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    MToast.showLongToast(getActivity(), "请先获取相机权限");
                }
            }, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttrEvent(LogisticsEvent event) {
        type = event.getMessageTag();
        if (event.getMessageTag() == EVENT_GET_COUNT) {
            binding.searchView.setVisibility(View.VISIBLE);
            binding.imgMore.setVisibility(View.VISIBLE);
        } else if (event.getMessageTag() == EVENT_GET_COUNT_TWO) {
            binding.searchView.setVisibility(View.GONE);
            binding.imgMore.setVisibility(View.GONE);
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
//    public void onEvent(MenuEvent event) {
//        if (event.getMessageTag() == EventConstant.EVENT_CHANGE_TAB) {
//            return;
//        }
//        int position = 0;
//        String s = event.getNo();
//        if (event.getMessageTag() == EventConstant.EVENT_BIG_HOME_JUMP) {
//            for (int i = 0; i < channelEntityList.size(); i++) {
//                if (channelEntityList.get(i).getName().equals(s)) {
//                    position = i;
//                }
//            }
//        }
//        binding.viewpager.setCurrentItem(position);
//    }

    /**
     * 切换城市的通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(ChooseAreaEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CHOOSE_AERA_Code) {
            ProvinceEntity<List<ProvinceEntity>> list = (ProvinceEntity<List<ProvinceEntity>>) event.getMessageData();
            selectCity(list);
        }
    }

    public void selectCity(ProvinceEntity<List<ProvinceEntity>> list) {
        if (list != null) {
            viewModel.saveProvinceModel(list);
        }
    }

    /**
     * 物流认证弹框
     */
    private void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_authentication, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失
        ImageView iv_hz = view.findViewById(R.id.iv_hz);
        ImageView iv_sj = view.findViewById(R.id.iv_sj);
        ImageView iv_close = view.findViewById(R.id.iv_close);

        //货主
        iv_hz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    AuthActivity3.start(getContext());
                }
                roundCornerDialog.dismiss();
            }
        });
        //司机
        iv_sj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (driverAuth.equals("NONE")) {
                /*    Intent intent = new Intent(getActivity(), AddVehicleActivity.class);
                    intent.putExtra("state", activity.state);
                    startActivityForResult(intent, 0);*/
                        //新司机认证页面
                        Intent intent = new Intent(getActivity(), AddDriverInfoActivity.class);
                        startActivity(intent);
                    } else {
                        AuthActivity3.start(getContext());
                    }
                }
                roundCornerDialog.dismiss();
            }
        });

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(CategoryEvent2 event) {
        if (event.getMessageTag() == EventConstant.EVENT_CATEGORY_CHOOSE2) {
            int id = (int) event.getMessageData();
            monitorClassification(id);
        }
    }

    public void monitorClassification(int id) {
        int curIndex = 0;
        for (int i = 0; i < channelEntityList.size(); i++) {
            if (channelEntityList.get(i).getId() == id) {
                curIndex = i;
                break;
            }
        }
        scrollToPositionWithOffset(curIndex, true);
    }

    public void scrollToPositionWithOffset(int position, boolean isJump) {
        int showSize = 2;
        ViewGroup vg = (ViewGroup) binding.tablayout.getChildAt(0);
        if (vg.getChildAt(0) != null){
            int width = vg.getChildAt(0).getWidth();
            if (position > showSize) {
                width *= position - showSize;
            } else {
                width *= 0;
            }
            binding.horizontalScrView.smoothScrollTo(width, 0);
            if (isJump) {
                binding.tablayout.getTabAt(position).select();
            }
        }
    }

    public MainActivity getMainActivity() {
        return activity;
    }

    /**
     * event监听登录和登出的状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGIN_OUT || event.getMessageTag() == EventConstant.EVENT_LOGIN) {
            //退出操作图片默认
            if (mCompanyData != null) {
                mCompanyData.clear();
            }
            if (tabSelectId == 6) {//物流
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    binding.tvZc.setVisibility(View.VISIBLE);
                }
            }
            mOriCompanyNo = "";
            refreshMemberTopStatus();
            if (event.getMessageTag() == EventConstant.EVENT_LOGIN) {
                binding.tvZc.setVisibility(View.GONE);
            }
        } else if (event.getMessageTag() == EventConstant.EVENT_START_LOCATION) {
            getLocation();
        }
    }

    /**
     * 著企业切换
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(String event) {
        if (event.equals(EventConstant.EVENT_REFRESH_MAIN)) {
            //  refreshMemberTopStatus();
        }
    }

    private void getLocation() {
        if (PermissionUtils.checkPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            viewModel.getLocation();
        }
    }

    /**
     * 商机信息查看权限判断
     *
     * @return ture 符合权限要求 false 否
     */
    public boolean isAuth() {
        List<String> authCompanyList = new ArrayList<>();
        authCompanyList.add("202004302544834");
        authCompanyList.add("1316637963131686912");
        authCompanyList.add("1321724009720713216");
        authCompanyList.add("202007211619262");
        authCompanyList.add("202004302544834");
        authCompanyList.add("202008148048453");
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            int type = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (type == 1) {
                String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                if (authCompanyList.contains(companyNo)) {
                    return true;
                } else {
                    MToast.showToast(getActivity(), "功能开发中，敬请期待");
                }
            } else {
                MToast.showToast(getActivity(), "功能开发中，敬请期待");
            }
        } else {
            MToast.showToast(getActivity(), "功能开发中，敬请期待");
        }
        return false;
    }


    public void refresh() {
        if (mPackersChangeFragment != null) {
            mPackersChangeFragment.refresh();
        }
    }

    /**
     * 顶部菜单栏数据变更提示弹框
     */
    public void showChannelChangeDialog() {
        ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_MENU_CHANGE, getActivity());
        ACAdminDialogUtils.showACBackDialog(ACAdminDialogUtils.TYPE_MENU_CHANGE, getActivity(), new ACAdminDialogUtils.DialogClick() {
            @Override
            public void dialogClick4() {
                PreferredChoiceActivity.start(getActivity(), false);
                if (activity != null)
                    activity.finish();
            }
        });
    }
}
